import FlagImage from '@/components/FlagImage';
import TagTags from '@/components/TagTags';
import * as c from '@/services/consts';
import * as apiGroup from '@/services/vpnGroup';
import * as apiEvent from '@/services/idcApiEvent';
import * as api from '@/services/vpnServerMonitor';
import * as utils from '@/utils/utils';
import {
  AreaChartOutlined,
  ArrowDownOutlined,
  ArrowRightOutlined,
  ArrowUpOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  EllipsisOutlined,
  PartitionOutlined,
  ProfileOutlined,
  ReloadOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable, {
  ActionType,
  ColumnsState,
  ProColumns,
  TableDropdown,
} from '@ant-design/pro-table';
import { Badge, Button, message, Popconfirm, Radio, Space, Tag, Modal, Tooltip } from 'antd';
import Paragraph from 'antd/es/typography/Paragraph';
import Countdown from 'antd/lib/statistic/Countdown';
import CheckableTag from 'antd/lib/tag/CheckableTag';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import GroupForm from '../VpnGroup/components/Form';
import VpnServerExportIpForm from '../VpnServer/components/VpnServerExportIpForm';
import VpnServerForm from '../VpnServer/components/VpnServerForm';
import CheckForm from '../VpnServerCheckLog/CheckForm';
import CheckReportForm from '../VpnServerCheckLog/CheckReportForm';
import GrafanaForm from './components/GrafanaForm';
import OnlineForm from './components/OnlineForm';
import ReportIpForm from './components/ReportIpsForm';
import CheckTaskForm from '../CheckTask/CheckForm';
// import ChangeIpForm from '../IdcApiEvent/ManualForm';
const dateFormat = 'YYYY-MM-DD';

const VpnGroupTreeList: React.FC = (props: any) => {
  // const { match } = props;
  // const paramOnline = parseInt(match.params.a, undefined);
  // console.log('location:', location, ' match: ', match, match?.params?.a);

  let paramOnline: any = utils.getStateValue('online');
  // console.log(paramOnline);

  const [dataLoading, setDataLoading] = useState<boolean>(true);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnServer | undefined>(undefined);
  const [productId, setProductId] = useState<string | undefined>(undefined);

  const [formGrafanaVisible, setFormGrafanaVisible] = useState<boolean>(false);
  // const [formChangeIpVisible, setFormChangeIpVisible] =useState<boolean>(false);
  const [currentNodeGroup, setCurrentNodeGroup] = useState<
    API.VpnGroupMonitorModel | undefined
  >(undefined);
  const [currentNode, setCurrentNode] = useState<
    API.VpnServerMonitorModel | undefined
  >(undefined);
  const [currentUrlGrafana, setCurrentUrlGrafana] = useState<
    string | undefined
  >(undefined);
  const [levelGroups, setLevelGroups] = useState<
    API.VpnGroupMonitorModel[] | undefined
  >(undefined);
  const [grafanaTitle, setGrafanaTitle] = useState<string | undefined>(
    undefined,
  );

  const [formCheckVisible, setFormCheckVisible] = useState<boolean>(false);
  const [formCheckReportVisible, setFormCheckReportVisible] =
    useState<boolean>(false);
  const [checkGroupIds, setCheckGroupIds] = useState<string[]>([]);
  // const [checkGroups, setCheckGroups] = useState<API.VpnGroupMonitorModel[]>([],);
  const [checkServerInstIds, setCheckServerInstIds] = useState<number[]>([]);
  const [checkServers, setCheckServers] = useState<API.VpnServerMonitorModel[]>(
    [],
  );

  const [formGroupVisible, setFormGroupVisible] = useState<boolean>(false);
  const [currentGroup, setCurrentGroup] = useState<
    API.VpnGroupMonitorModel | undefined
  >(undefined);
  const [formOnlineVisible, setFormOnlineVisible] = useState<boolean>(false);
  const [currentOnlineCode, setCurrentOnlineCode] = useState<
    string | undefined
  >(undefined);
  const [formExportIpVisible, setFormExportIpVisible] =
    useState<boolean>(false);
  const [formReportIpVisible, setFormReportIpVisible] =
    useState<boolean>(false);

  const [filterAreaPolicy, setFilterAreaPolicy] = useState<number | undefined>(
    undefined,
  );
  const [filterDisableGroup, setFilterDisableGroup] = useState<boolean>(true);
  const [filterDisableServer, setFilterDisableServer] = useState<boolean>(true);
  const [filterOnline, setFilterOnline] = useState<number | undefined>(
    paramOnline,
  );
  const [currentVer, setCurrentVer] = useState<string | undefined>(undefined);

  const [countdownTicks, setCountdownTicks] = useState<number>(
    Date.now() + 60000,
  );
  
  const [monitorData, setMonitorData] = useState<
    API.VpnGroupMonitorList | undefined
  >(undefined);
  const [controlState, setControlState] = useState<number>(0);

  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >({
    // 'areaPolicy':{show:false},
    displayAppVerComparePolicy: { show: false },
    displayPlatforms: { show: false },
    displayChannels: { show: false },
  });
  const [selectedTags, setSelectedTags] = useState<string[]>([
    'group',
    'server',
  ]);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { hasRight } = useModel('useAuthModel');

  const {
    getProduct,
    getProductMenuItems,
    getSupplier,
    getGroupAreaFilterPolicyText,
    reloadVpnGroupTrees,
    globalGrafanaModel,
  } = useModel('useGlobalModel', (model) => ({
    getProduct: model.getProduct,
    getProductMenuItems: model.getProductMenuItems,
    getSupplier: model.getSupplier,
    getGroupAreaFilterPolicyText: model.getGroupAreaFilterPolicyText,
    reloadVpnGroupTrees: model.reloadVpnGroupTrees,
    globalGrafanaModel: model.globalGrafanaModel,
  }));

  const productMenuItems = getProductMenuItems(true);
  const alertGreen = 104857600; //100*1024*1024
  const alertOrange = 209715200; //200*1024*1024
  // const alertOrangeMb = 250;//200 / 0.8; //200*1024*1024
  const [formCheckTaskVisible, setFormCheckTaskVisible] = useState<boolean>(false);


  const reload = () => {
    // if (countdownTicks > 0) {
    setControlState(new Date().getTime());
    // setCountdownTicks(Date.now() + customCountdownTicks);
    setCountdownTicks(Date.now() + 60000);
    // }
  };

  const loadDataDo = async () => {
    const result = await api.list(
      {
        productIds:
          productId && productId !== c.DefaultOptionAll.key
            ? parseInt(productId)
            : undefined,
        areaPolicy: filterAreaPolicy,
        disableGroup: filterDisableGroup,
        disableServer: filterDisableServer,
        online: filterOnline,
      },
      undefined,
      undefined,
    );

    if (result && result.success) {
      setMonitorData(result);
    } else {
      // setMonitorData([]);
      setMonitorData(undefined);
    }
    setDataLoading(false);
  };

  useEffect(() => {
    loadDataDo();
  }, [controlState, productId]);


  const handleCheckGroup = async (model: API.VpnGroupMonitorModel) => {
    if (!checkGroupIds.includes(model.id)) {
      let ids = checkGroupIds.concat([model.id]);
      // console.log(ids);
      setCheckGroupIds(ids);
      // setCheckGroups(checkGroups.concat(model));
      message.info('设置成功，等待下发');
    } else {
      message.info('已经存在');
    }
  };

  const handleCheckServer = async (model: API.VpnServerMonitorModel) => {
    if (!checkServerInstIds.includes(model.instanceId)) {
      let ids = checkServerInstIds.concat([model.instanceId]);
      // console.log(ids);
      setCheckServerInstIds(ids);
      setCheckServers(checkServers.concat(model));
      message.info('设置成功，等待下发');
    } else {
      message.info('已经存在');
    }
  };

  const handleFilterAreaPolicy = (val: number | undefined) => {
    setFilterAreaPolicy(val);
    setDataLoading(true);
    reload();
  };

  const handleFilterOnline = (val: number | undefined) => {
    setFilterOnline(val);
    setDataLoading(true);
    reload();
  };

  const checkFormSubmit = async () => {
    setFormCheckVisible(false);
    setCheckGroupIds([]);
    setCheckServerInstIds([]);
    // setCheckGroups([]);
    setCheckServers([]);
  };

  const handleFormGroupSubmit = async (
    record: API.VpnGroupModel | API.VpnGroupMonitorModel,
  ) => {
    record.mutiLangs = record.mutiLangs ? record.mutiLangs : {};
    if (!record.userLimit) {
      record.userLimit = undefined;
    }
    let d: API.VpnGroupModel = {
      id: record.id, // ?? currentGroup?.id,
      name: record.name, // ?? currentGroup?.name,
      code: record.code, // ?? currentGroup?.code,
      mutiLang: record.mutiLang, // ?? currentGroup?.mutiLang,
      flag: record.flag, // ?? currentGroup?.flag,
      type: record.type, // ?? currentGroup?.type,
      memberLevel: record.memberLevel, // ?? currentGroup?.memberLevel,
      userLimit: record.userLimit, //  ?? currentGroup?.userLimit,
      sort: record.sort, //  ?? currentGroup?.sort,
      tags: record.tags, // ?? currentGroup?.tags,
      parentId: record.parentId, // ?? currentGroup?.parentId,
      preBridgeGroupIds: record.preBridgeGroupIds,
      display: record.display,
      status: record.status, // ?? currentGroup?.status,
      remark: record.remark, // ?? currentGroup?.remark,
      changeIp: record.changeIp, // ?? currentGroup?.changeIp,
      changeIpCount: record.changeIpCount,
      policy: record.policy, // ?? currentGroup?.policy,
      allotMode: record.allotMode, // ?? currentGroup?.allotMode,
      allotConfig: record.allotConfig, // ?? currentGroup?.allotConfig,
      protocol: record.protocol, // ?? currentGroup?.protocol,
      productIds: record.productIds, // ??  currentGroup?.productIds,
      productIdsText: '',
      parentSort: 0,
      secondSort: 0,
      serverCount: 0,
      validServerCount: 0,
      userCount: 0,
    };

    // console.log(d);
    // return;

    let result = await apiGroup.update({
      // ...currentGroup,
      // ...record,
      ...d,
    });

    if (result && result.success === true) {
      setCurrentGroup(undefined);
      setFormGroupVisible(false);
      setDataLoading(true);
      reload();

      //更新缓存
      await reloadVpnGroupTrees();
    }
  };

  const handleTagChange = (tag: string, checked: boolean) => {
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag);
    setSelectedTags(nextSelectedTags);
    if (tag == 'group') {
      setFilterDisableGroup(checked);
    } else if (tag == 'server') {
      setFilterDisableServer(checked);
    }
    setDataLoading(true);
    reload();
  };

  const alertRateMb = (
    rate: number | undefined,
    rateTotal: number | undefined,
    per1: number,
    per2: number,
    isByte: boolean,
  ) => {
    if (!rate) return 0;
    if (isByte == false) {
      rate = rate / 8;
    }
    rate = rate / 1024 / 1024;

    rateTotal = rateTotal ?? 250; //200 /0.8

    // console.log(rate, rateTotal, rateTotal * per1, rateTotal * per2);

    let ar = rate > rateTotal * per1;
    if (ar == true) {
      ar = rate > rateTotal * per2;
      if (ar == true) {
        return 3;
      } else {
        return 2;
      }
    }
    return 1;
  };

  const handleChangeIp = async (supplierId: number|undefined, instId: number | undefined) => {
    if(!supplierId){
      message.error("该服务器没有提供商");
      return;
    }

    let supplier = getSupplier(supplierId);
    if(!supplier){
      message.error("未找到该服务器提供商");
      return;
    }
    if(!supplier.code){
      message.error("该服务器提供商未设置代码");
      return;
    }

    if(!instId){
      message.error("请选择检测内容");
      return;
    }

    let record: API.IdcApiEventForm = {
      code: supplier.code,
      action: c.IdcApiEventAction.ChangeIp.value,
      instanceIds: instId.toFixed()
    };

    // console.log(record);
    // return false;
    const result = await apiEvent.add(record);
    if (result && result.success) {
      message.success("下发成功，等待处理中");
      reload();
    }
  };


  let columns: ProColumns<API.VpnGroupMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    // {
    //   title: '产品',
    //   // align: 'center',
    //   width: 90,
    //   dataIndex: 'productIdsText',
    //   // sorter: (a, b) => (a.parentId ?? '').localeCompare(b.parentId ?? ''),
    //   renderText: (_, record) => {
    //     if (record.productIds) {
    //       let text = '';
    //       for (let i = 0; i < record.productIds.length; i++) {
    //         const product = getProduct(record.productIds[i]);
    //         if (product) {
    //           if (text != '') {
    //             text += '/';
    //           }
    //           text += product.name;
    //         }
    //       }

    //       return text;
    //     }
    //     return '';
    //   },
    // },
    {
      title: '等级',
      align: 'center',
      width: 60,
      dataIndex: 'memberLevel',
      sorter: (a, b) => (a.memberLevel ?? 0) - (b.memberLevel ?? 0),
      renderText: (val) => {
        return c.getMemberLevelText(val);
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      width: 300,
      render: (text, record) => {
        // let title = `${text}`;
        let title = (<>{text}[{record.code}]</>);

        // if(record.protocol){
        //   title = <span style={{color:record.protocol == 3 ? '#54ba05' : record.protocol == 1 ? "blue" : record.protocol == 2 ? "#c08af3" : ""}}>{text}</span>;
        // }

        // if (record.children != null) {
        //   title += ` (${record.serverCount}/${record.children.length})`;
        // } else {
        //   title += ` (${record.serverCount})`;
        // }

        return (
          <>
            <Space>
              <Paragraph
                copyable={{ text: text.toString() }}
                style={{ marginBottom: 0 }}
              >
                <FlagImage flagName={record.flag} />
                {record.display != true ? <Tag>{title}</Tag> : title}{' '}
                {record.preBridgeGroups && record.preBridgeGroups.length > 0 ? <Tag color="blue">桥接</Tag> : ''}
                {record.changeIp > 0 ? (<Tag color="blue">{record.changeIp}分钟</Tag>) : ('')}

                {record.type == c.VpnGroupType.Ghost.value ? (
                  <>
                    <Tag color="green" style={{marginLeft: 5,}}>
                      {c.getVpnGroupTypeText(record.type)}
                    </Tag>
                  </>
                ) : ''}

              </Paragraph>
            </Space>
            <a
              key="check_group_title"
              onClick={(e) => {
                handleCheckGroup(record);
              }}
            >
              <PartitionOutlined style={{ color: '#999', marginLeft: 5 }} />
            </a>
          </>
        );
      },
    },
    {
      title: '启用/总数',
      // align: 'center',
      dataIndex: 'validServerCount',
      width: 100,
      sorter: (a, b) => (a.validServerCount ?? 0) - (b.validServerCount ?? 0),
      renderText: (_, record) => {
        if (record.validServerCount == 0) {
          return (
            <Tag color="red">
              {record.validServerCount}/{record.serverCount}
            </Tag>
          );
        }
        return `${record.validServerCount}/${record.serverCount}`;
      },
    },
    {
      title: '在线/离线',
      // align: 'center',
      dataIndex: 'onlineCount',
      width: 100,
      sorter: (a, b) => (a.onlineCount ?? 0) - (b.onlineCount ?? 0),
      renderText: (_, record) => {
        if (record.onlineCount == 0) {
          return (
            <Tag color="red">
              {record.onlineCount}/{record.offlineCount}
            </Tag>
          );
        }
        return (
          <>
            {record.onlineCount}/
            {record.offlineCount ? (
              <span style={{ color: '#f50', fontWeight: 'bold' }}>
                {record.offlineCount}
              </span>
            ) : (
              record.offlineCount
            )}
          </>
        );
      },
    },
    {
      title: 'IP总/禁/墙/出',
      // align: 'center',
      dataIndex: 'ipCount',
      width: 120,
      sorter: (a, b) => (a.ipCount ?? 0) - (b.ipCount ?? 0),
      renderText: (_, record) => {
        return (
          <>
            {record.ipCount}/
            {record.ipDisableCount ? (
              <span style={{ color: '#f50', fontWeight: 'bold' }}>
                {record.ipDisableCount}
              </span>
            ) : (
              record.ipDisableCount
            )}
            /
            {record.ipBlockCount ? (
              <span style={{ color: 'orange', fontWeight: 'bold' }}>
                {record.ipBlockCount}
              </span>
            ) : (
              record.ipBlockCount
            )}
            /{record.ipRelayCount}
          </>
        );
      },
    },
    {
      title: '在线用户/限制',
      dataIndex: 'userCount',
      // align: 'center',
      width: 150,
      sorter: (a, b) => (a.userCount ?? 0) - (b.userCount ?? 0),
      render: (_, record) => {
        return (
          <>
            {utils.formatNumber(record.userCount)}
            {record.userLimit ? (
              <span>
                /
                <span style={{ color: 'orange', fontWeight: 'bold' }}>
                  {utils.formatNumber(record.userLimit)}
                </span>
              </span>
            ) : (
              ''
            )}
            <a
              key="online_chart"
              onClick={(e) => {
                setFormOnlineVisible(true);
                setCurrentGroup(record);
                setCurrentOnlineCode(undefined);
              }}
            >
              &nbsp;
              <AreaChartOutlined />
            </a>
            <a
              key="online_ips"
              onClick={(e) => {
                setFormReportIpVisible(true);
                setCurrentGroup(record);
                setCurrent(undefined);
              }}
            >
              &nbsp;
              <ProfileOutlined />
            </a>
          </>
        );
      },
    },
    {
      title: '下载',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 100,
      render: (_, record) => {
        let val = 0;
        if (record.maxBandwidth) {
          val = alertRateMb(
            record.download,
            record.maxBandwidth,
            0.7,
            0.9,
            true,
          );
        } else {
          val =
            record.upload && record.validServerCount > 0
              ? record.upload / record.validServerCount
              : 0;
          val =
            val == 0 ? 0 : val <= alertGreen ? 1 : val <= alertOrange ? 2 : 3;
        }
        return (
          <Tag
            color={
              val == 3 ? 'red' : val == 2 ? 'orange' : val == 1 ? 'green' : ''
            }
          >
            <b>
              <ArrowDownOutlined /> {utils.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 125,
      render: (_, record) => {
        let val = 0;
        if (record.maxBandwidth) {
          val = alertRateMb(record.upload, record.maxBandwidth, 0.7, 0.9, true);
        } else {
          val =
            record.upload && record.validServerCount > 0
              ? record.upload / record.validServerCount
              : 0;
          val =
            val == 0 ? 0 : val <= alertGreen ? 1 : val <= alertOrange ? 2 : 3;
        }
        return (
          <span>
            <Tag
              color={
                val == 3 ? 'red' : val == 2 ? 'orange' : val == 1 ? 'green' : ''
              }
            >
              <b>
                <ArrowUpOutlined /> {utils.formatRate(record.upload, true)}
              </b>
            </Tag>
            <a
              key="edit"
              onClick={(e) => {
                // setFormNodeGroupVisible(true);
                // setCurrentNodeGroup(record);
                setFormGrafanaVisible(true);
                setCurrentNode(undefined);
                setCurrentNodeGroup(record);
                // setCurrentUrlGrafana(urlGrafanaNodeGroup);
                setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNodeGroup);
                setLevelGroups(undefined);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: '分组代码',
      dataIndex: 'code',
      width: 90,
      sorter: (a, b) => (a.code ?? '').localeCompare(b.code ?? ''),
      render: (_, record) => {
        return (
          <>
            {record.preBridgeGroups.length > 0 ? (
              <div>
                {record.preBridgeGroups?.map((val) => (
                  <Tag color="blue">{val.code}</Tag>
                ))}
              </div>
            ) : (
              ''
            )}
            <div>
              {record.preBridgeGroups.length > 0 ? <ArrowRightOutlined /> : ''}
              {record.code}
            </div>
          </>
        );
      },
    },
    {
      title: '支持协议',
      // align: 'center',
      dataIndex: 'protocol',
      sorter: true,
      width: 90,
      renderText: (val) => {
        return val ? (
          <Tag color="blue">{c.getObjectText(c.VpnGroupProtocols, val)}</Tag>
        ) : (
          ''
        );
      },
    },
    {
      title: '版本策略',
      dataIndex: 'displayAppVerComparePolicy',
      width: 80,
      // align: 'center',
      sorter: false,
      renderText: (_, record) => {
        if (
          record.policy != null &&
          record.policy.displayAppVerComparePolicy &&
          record.policy.displayAppVerComparePolicy != '' &&
          record.policy.displayAppVerComparePolicyAppVer > 0
        ) {
          return `${record.policy.displayAppVerComparePolicy}${record.policy.displayAppVerComparePolicyAppVer}`;
        }
        return null;
      },
    },
    {
      title: '平台策略',
      dataIndex: 'displayPlatforms',
      width: 80,
      sorter: false,
      renderText: (_, record) => {
        return record.policy?.displayPlatforms?.join(',');
      },
    },
    {
      title: '渠道策略',
      dataIndex: 'displayChannels',
      width: 80,
      sorter: false,
      renderText: (_, record) => {
        return record.policy?.displayChannels?.join(',');
      },
    },
    {
      title: '地区策略',
      width: 120,
      dataIndex: 'areaPolicy',
      sorter: false,
      render: (_, record) => {
        let policy = getGroupAreaFilterPolicyText(record.policy);
        return policy ? (
          <Tag color={policy.indexOf('显示') == -1 ? '' : 'blue'}>{policy}</Tag>
        ) : (
          policy
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      width: 120,
      render: (_, record) => <TagTags values={record.tags} />,
    },
    {
      title: '排序',
      align: 'center',
      width: 60,
      dataIndex: 'sort',
      sorter: (a, b) => (a.sort ?? 0) - (b.sort ?? 0),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
      sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
    },
    // {
    //   title: '检测',
    //   dataIndex: 'checkPercent',
    //   width:80,
    //   render: (_, record) => {
    //     return(
    //       record.checkPercent ? record.checkPercent == 100 ? <Tag color='success'>完成</Tag> : <Tag color="blue">{record.checkPercent} %</Tag> : ''
    //     )
    //   },
    // },
    {
      title: '最后检测',
      dataIndex: 'checkTime',
      width: 100,
      render: (_, record) => {
        let text = <>大于7天</>;
        let today = dayjs(new Date()).format(dateFormat);
        let yesterday = dayjs(new Date()).add(-1, 'days').format(dateFormat);
        let before_yesterday = dayjs(new Date())
          .add(-2, 'days')
          .format(dateFormat);
        if (record.checkTime) {
          if (today == dayjs(record.checkTime).format(dateFormat)) {
            text = (
              <Tag color="green">
                今天 {dayjs(record.checkTime).format('HH:mm:ss')}
              </Tag>
            );
          } else if (yesterday == dayjs(record.checkTime).format(dateFormat)) {
            text = (
              <Tag color="cyan">
                昨天 {dayjs(record.checkTime).format('HH:mm:ss')}
              </Tag>
            );
          } else if (
            before_yesterday == dayjs(record.checkTime).format(dateFormat)
          ) {
            text = <>前天 {dayjs(record.checkTime).format('HH:mm:ss')}</>;
          } else {
            text = <>{dayjs(record.checkTime).format('MM-DD HH:mm:ss')}</>;
          }
        }
        return text;
        // record.checkTime ? dayjs(record.checkTime).format("MM-DD HH:mm:ss") : "大于3天"
      },
      // sorter: (a, b) =>utils.formatUtcToLocal(a.checkTime).localeCompare(utils.formatUtcToLocal(b.checkTime)),
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 105,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpngroup_update')) {
          cmps.push(
            <a
              key="edit_group"
              onClick={(e) => {
                setCountdownTicks(-1);
                setFormGroupVisible(true);
                setCurrentGroup(record);
              }}
            >
            编辑
            </a>,
          );
        }

        if (hasRight('vpnserver_update') && record.status == true) {
          cmps.push(
            <a
              key="check"
              onClick={(e) => {
                handleCheckGroup(record);
              }}
            >
              检测
            </a>,
          );
        }

        // if (hasRight('vpnserver_update')) {
        //   cmps.push(
        //     <a
        //       key="check_report"
        //       onClick={(e) => {
        //         setCurrentVer(record.checkVer);
        //         setFormCheckReportVisible(true);
        //         setCurrentNodeGroup(record);
        //       }}
        //     >
        //       检测结果
        //     </a>,
        //   );
        // }
        cmps.push(
          <TableDropdown
            key="actionGroup"
            onSelect={(key) => {
              // console.log(key);
              switch (key) {
                // case 'edit_group':
                //   setCountdownTicks(-1);
                //   setFormGroupVisible(true);
                //   setCurrentGroup(record);
                // break;
                case 'check_report':
                  setCurrentVer(record.checkVer);
                  setFormCheckReportVisible(true);
                  setCurrentNodeGroup(record);
                  break;
              }
            }}
            menus={[
              { key: 'check_report', name: '检测结果' },
              // { key: 'edit_group', name: '编辑分组' },
            ]}
          />,
        );

        return cmps;
      },
    },
  ]);

  let childrenColumns: ProColumns<API.VpnServerMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      // sorter: true,
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '实例ID',
      // align: 'center',
      width: 90,
      dataIndex: 'instanceId',
      //sorter: true,
      sorter: (a, b) => a.instanceId - b.instanceId,
      render: (_, record) => {
        return record.unscheduled == true ? (
          <Tag color="gold">{record.instanceId}</Tag>
        ) : (
          record.instanceId
        );
      },
    },
    {
      title: '类型',
      align: 'center',
      width: 70,
      dataIndex: 'serverType',
      //sorter: true,
      sorter: (a, b) => (a.serverType ?? 0) - (b.serverType ?? 0),
      render: (_, record) => {
        return c.getServerType(record.serverType)?.label;
      },
    },
    {
      title: '供应商',
      align: 'center',
      width: 100,
      dataIndex: 'supplierId',
      //sorter: true,
      sorter: (a, b) => (a.supplierId ?? 0) - (b.supplierId ?? 0),
      render: (_, record) => {
        return getSupplier(record.supplierId)?.name;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 250,
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      render: (_, record) => {
        return (
          <>
          <div>
            {record.name}
            <a
              key="check_node_title"
              onClick={(e) => {
                handleCheckServer(record);
              }}
            >
              <PartitionOutlined style={{ color: '#999', marginLeft: 5 }} />
            </a>
          </div>
          {record.serverInfo?.serverName ? <div><Tag color='blue'>{record.serverInfo?.serverName}</Tag></div> : ''}
          </>
        );
      },
    },
    {
      title: 'IP总/禁/墙/出',
      dataIndex: 'ip',
      width: 200,
      sorter: (a, b) => (a.ip ?? '').localeCompare(b.ip ?? ''),
      render: (_, record) => {
        return (
          <>
          <div>
            {record.blockedIp == true ||
            (record.remark && record.remark.indexOf('被墙') != -1) ? (
              <span style={{ color: 'orange' }}>{record.ip}</span>
            ) : (
              record.ip
            )}{' '}
            {record.ipCount == 0 ? (
              ''
            ) : (
              <>
                {' '}
                ({record.ipCount}/
                {record.ipDisableCount ? (
                  <span style={{ color: '#f50', fontWeight: 'bold' }}>
                    {record.ipDisableCount}
                  </span>
                ) : (
                  record.ipDisableCount
                )}
                /
                {record.ipBlockCount ? (
                  <span style={{ color: 'orange', fontWeight: 'bold' }}>
                    {record.ipBlockCount}
                  </span>
                ) : (
                  record.ipBlockCount
                )}
                /{record.ipRelayCount})
              </>
            )}
            </div>

            {record.serverInfo?.changeIpStatus || record.serverInfo?.changeIpLastStatus == 2 || record.serverInfo?.changeIpLastStatus == 3 ?
            <div>
              <Tooltip color='grey' title={<>
              {record.serverInfo?.changeIpStatus == 1 ? <>
              <div>下发时间：{utils.formatDate(record.serverInfo?.changeIpTime)}</div>
              <div>下发人员：{record.serverInfo?.changeIpUser}</div>
              </> : ''}
              {record.serverInfo.changeIpLastTime ? <>
              <div>上次更换状态：<Tag color={record.serverInfo?.changeIpLastStatus == 2 ? 'success' : 'error'}>{record.serverInfo?.changeIpLastStatus == 2 ? '成功' : '失败'}</Tag></div>
              <div>上次更换时间：{utils.formatDate(record.serverInfo?.changeIpLastTime)}</div>
              <div>上次更换人员：{record.serverInfo?.changeIpLastUser}</div>
              </> : ''}
              </>}>

              {record.serverInfo?.changeIpStatus == 1 ?
                <Tag color='blue'>IP更换中 / {utils.formatDate(record.serverInfo?.changeIpTime, 'MM-DD HH:mm:ss')}</Tag>
              : record.serverInfo?.changeIpLastStatus == 3 ?
                <Tag color='error'>更换失败 / {utils.formatDate(record.serverInfo?.changeIpLastTime, 'MM-DD HH:mm:ss')}</Tag> :
              <><div><Tag color={dayjs(new Date()).format('YYYY-MM-DD') != dayjs(record.serverInfo?.changeIpLastTime).format('YYYY-MM-DD') ? '' : 'success'}>
                老: {record.serverInfo?.changeIpOld} / {utils.formatDate(record.serverInfo?.changeIpLastTime, 'MM-DD HH:mm:ss')}</Tag></div>
              </>}
              </Tooltip>
            </div>
            : ''}
          </>
        );
      },
    },
    {
      title: '在线',
      align: 'center',
      width: 60,
      dataIndex: 'online',
      sorter: (a, b) => (a.online == true ? 1 : 0) - (b.online == true ? 1 : 0),
      render: (_, record) => {
        return (
          <>
            {record.online ? (
              <Badge
                count={<CheckCircleFilled style={{ color: '#52c41a' }} />}
              />
            ) : (
              <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
            )}
            {record.online == false && record.updateTime ? (
              <div>{record.updateTime}</div>
            ) : (
              ''
            )}
          </>
        );
      },
    },
    {
      title: '在线用户',
      dataIndex: 'userCount',
      // align: 'center',
      //sorter: true,
      sorter: (a, b) => (a.userCount ?? 0) - (b.userCount ?? 0),
      width: 90,
      render: (_, record) => {
        return (
          <>
            {record.userCount}
            <a
              key="online_ips"
              onClick={(e) => {
                setFormReportIpVisible(true);
                setCurrentGroup(undefined);
                setCurrent(record);
              }}
            >
              &nbsp;
              <ProfileOutlined />
            </a>
          </>
        );
      },
    },
    {
      title: '下载',
      // align: 'center',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 100,
      render: (_, record) => {
        return (
          <Tag
            color={
              record.download
                ? record.download <= alertGreen
                  ? 'green'
                  : record.download <= alertOrange
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              <ArrowDownOutlined /> {utils.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      // align: 'center',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 120,
      render: (_, record) => {
        return (
          <span>
            <Tag
              color={
                record.upload
                  ? record.upload <= alertGreen
                    ? 'green'
                    : record.upload <= alertOrange
                    ? 'orange'
                    : 'red'
                  : ''
              }
            >
              <b>
                <ArrowUpOutlined /> {utils.formatRate(record.upload, true)}
              </b>
            </Tag>

            <a
              key="edit"
              onClick={(e) => {
                // setFormNodeVisible(true);
                // setCurrentNode(record);
                setFormGrafanaVisible(true);
                setCurrentNode(record);
                setCurrentNodeGroup(undefined);
                // setCurrentUrlGrafana(urlGrafanaNode);
                setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNode);
                setLevelGroups(undefined);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: 'CPU',
      // align: 'center',
      dataIndex: 'cpuUsed',
      width: 100,
      sorter: (a, b) => (a.cpuUsed ?? 0) - (b.cpuUsed ?? 0),
      render: (_, record) => {
        return (
          <Tag
            color={
              record.cpuUsed
                ? record.cpuUsed < 0.5
                  ? 'green'
                  : record.cpuUsed < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {record.cpuCore} / {utils.formatPercentage(record.cpuUsed, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '内存',
      dataIndex: 'memUsedPer',
      // align: 'center',
      width: 120,
      sorter: (a, b) => (a.memUsedPer ?? 0) - (b.memUsedPer ?? 0),
      render: (_, record) => {
        let usedPer = record.memUsedPer ?? 0;
        return (
          <Tag
            color={
              usedPer != 0
                ? usedPer < 0.5
                  ? 'green'
                  : usedPer < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {utils.formatRate(record.memTotal, true)} /{' '}
              {utils.formatPercentage(usedPer, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '版本',
      dataIndex: 'version',
      // align: 'center',
      width: 60,
      sorter: (a, b) => (a.version ?? '').localeCompare(b.version ?? ''),
    },
    {
      title: '启动时间',
      // align: 'center',
      dataIndex: 'startTime',
      sorter: (a, b) =>
        utils
          .formatUtcToLocal(a.startTime)
          .localeCompare(utils.formatUtcToLocal(b.startTime)),
      width: 160,
      render: (_, record) => utils.formatUtcToLocal(record.startTime),
    },
    // {
    //   title: '运行时长',
    //   align: 'center',
    //   dataIndex: 'runSeconds',
    //   sorter: (a, b) =>
    //     utils
    //       .formatDuration(a.runSeconds)
    //       .localeCompare(utils.formatDuration(b.runSeconds)),
    //   width: 100,
    //   render: (_, record) =>
    //     record.runSeconds > 0 ? utils.formatDuration(record.runSeconds) : '',
    // },
    {
      title: '带宽限制',
      // align: 'center',
      dataIndex: 'maxBandwidth',
      width: 90,
      sorter: (a, b) => (a.maxBandwidth ?? 0) - (b.maxBandwidth ?? 0),
      render: (_, record) => {
        return (
          <>
            {(record.maxBandwidth as number) > 0
              ? `T:${record.maxBandwidth}`
              : ''}
            {(record.maxUserBandwidth as number) > 0
              ? ` U:${record.maxUserBandwidth}`
              : ''}
          </>
        );
      },
    },
    {
      title: '价格',
      // align: 'center',
      dataIndex: 'price',
      width: 60,
      // sorter: (a, b) => ((a.serverInfo?.price) ?? 0) - ((b.serverInfo?.price) ?? 0),
      render: (_, record) => {
        return record.serverInfo?.price;
      },
    },
    {
      title: '上架日期',
      // align: 'center',
      dataIndex: 'addedDate',
      width: 90,
      render: (_, record) => {
        return <><div>{record.addedDate
          ? dayjs(record.addedDate).format(dateFormat)
          : ''}</div>
          <div>{record.createUser}</div>
          </>;
      },
    },
    // {
    //   title: '上架人',
    //   dataIndex: 'createUser',
    //   width: 100,
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
      ellipsis: true,
    },
  ];

  childrenColumns = childrenColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 115,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpnserver_update')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要换IP吗?"
              onConfirm={async () => {
                await handleChangeIp(record.supplierId, record.instanceId);
              }}
            >
              <a>换IP</a>
            </Popconfirm>,


            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('vpnserver_update')) {
          cmps.push(
            <a
              key="check"
              onClick={(e) => {
                handleCheckServer(record);
              }}
            >
              检测
            </a>,
            // <Popconfirm
            //   key="check"
            //   title="确定要检测该服务器吗?"
            //   onConfirm={async () => {
            //     await handleCheck("server", record.id);
            //   }}
            // >
            //   <a>检测</a>
            // </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable<API.VpnGroupMonitorModel>
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        options={{
          fullScreen: false,
          reload: false,
          // setting: false,
          density: false,
          // search:true,
          // setting: {
          //   listsHeight: 500,
          // },
        }}
        loading={dataLoading}
        search={false}
        pagination={false}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        expandable={{
          expandedRowRender: (record) => (
            <ProTable
              columns={childrenColumns}
              headerTitle={false}
              search={false}
              options={false}
              dataSource={record.data}
              tableStyle={{ marginLeft: 10 }}
              // pagination={false}
              pagination={{
                defaultPageSize: 50,
                pageSizeOptions: [
                  '50',
                  '100',
                  '200',
                  '300',
                  '500',
                  '1000',
                  '2000',
                  '5000',
                  '10000',
                ],
                hideOnSinglePage: false,
                // current: pageCurrent,
                // total: totalCount,
              }}
            />
            // <MyVirtualTable columns={childrenVirtualColumns} dataSource={record.data} scroll={{ y: 54 * record.data.length + 100, x: '100vw' }} />
          ),
          defaultExpandedRowKeys: ['0'],
        }}
        //toolBarRender
        title={() => [
          <Space
            style={{
              marginRight: '0px',
              // width: 1500,
              justifyContent: 'right',
              backgroundColor:'red'
            }}
          >
            <Space>
              <span>
                <Radio.Group
                  defaultValue={
                    filterOnline == 1 ? 'b' : filterOnline == 0 ? 'c' : 'a'
                  }
                  buttonStyle="solid"
                >
                  <Radio.Button
                    value="a"
                    onClick={() => {
                      handleFilterOnline(undefined);
                    }}
                  >
                    全部
                  </Radio.Button>
                  <Radio.Button
                    value="b"
                    onClick={() => {
                      handleFilterOnline(1);
                    }}
                  >
                    在线
                  </Radio.Button>
                  <Radio.Button
                    value="c"
                    onClick={() => {
                      handleFilterOnline(0);
                    }}
                  >
                    离线
                  </Radio.Button>
                </Radio.Group>
              </span>

              <span>
                <b>流量&nbsp;</b>
                <a
                  onClick={(e) => {
                    setFormGrafanaVisible(true);
                    setCurrentNode(undefined);
                    setCurrentNodeGroup(undefined);
                    // setCurrentUrlGrafana(urlGrafanaNodeAll);
                    setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNodeAll);
                    setLevelGroups(undefined);
                  }}
                >
                  <AreaChartOutlined />总
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    <ArrowDownOutlined />
                    {utils.formatRate(monitorData?.totalDownload, true)}
                    {/* {utils.formatRate(totalDownload, true)} */}
                    &nbsp;&nbsp;
                    <ArrowUpOutlined />
                    {utils.formatRate(monitorData?.totalUpload, true)}
                    {/* {utils.formatRate(totalUpload, true)} */}
                  </b>
                </Tag>
                {/* &nbsp; */}
                <a
                  onClick={(e) => {
                    let groups: API.VpnGroupMonitorModel[] = [];
                    monitorData?.data.forEach((item) => {
                      if (item.memberLevel != 0 && item.memberLevel != 1) {
                        groups.push(item);
                      }
                    });
                    setLevelGroups(groups);
                    setGrafanaTitle('VIP分组总流量');

                    setFormGrafanaVisible(true);
                    setCurrentNode(undefined);
                    setCurrentNodeGroup(undefined);
                    setCurrentUrlGrafana(
                      globalGrafanaModel?.urlGrafanaNodeGroup,
                    );
                  }}
                >
                  <AreaChartOutlined />
                  VIP
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    <ArrowDownOutlined />
                    {utils.formatRate(monitorData?.totalVipDownload, true)}
                  </b>
                  &nbsp;&nbsp;
                  <b>
                    <ArrowUpOutlined />
                    {utils.formatRate(monitorData?.totalVipUpload, true)}
                  </b>
                </Tag>
                {/* &nbsp; */}
                <a
                  onClick={(e) => {
                    let groups: API.VpnGroupMonitorModel[] = [];
                    monitorData?.data.forEach((item) => {
                      if (item.memberLevel == 0 || item.memberLevel == 1) {
                        groups.push(item);
                      }
                    });
                    setLevelGroups(groups);
                    setGrafanaTitle('Free分组总流量');

                    setFormGrafanaVisible(true);
                    setCurrentNode(undefined);
                    setCurrentNodeGroup(undefined);
                    setCurrentUrlGrafana(
                      globalGrafanaModel?.urlGrafanaNodeGroup,
                    );
                  }}
                >
                  <AreaChartOutlined />
                  Free
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    <ArrowDownOutlined />
                    {utils.formatRate(monitorData?.totalFreeDownload, true)}
                  </b>
                  &nbsp;&nbsp;
                  <b>
                    <ArrowUpOutlined />
                    {utils.formatRate(monitorData?.totalFreeUpload, true)}
                  </b>
                </Tag>
                &nbsp;
                <a
                  key="online_chart_total"
                  onClick={(e) => {
                    setFormOnlineVisible(true);
                    setCurrentGroup(undefined);
                    setCurrentOnlineCode('__total__');
                  }}
                >
                  {/* <AreaChartOutlined />
                  在线用户 */}
                  <UserOutlined />
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    {/* {utils.formatNumber(totalUserCount)} [F:
                {utils.formatNumber(totalFreeUserCount)} / V:
                {utils.formatNumber(totalVipUserCount)}] */}
                    {utils.formatNumber(monitorData?.totalUserCount)} [
                    <a
                      key="online_chart_free"
                      onClick={(e) => {
                        setFormOnlineVisible(true);
                        setCurrentGroup(undefined);
                        setCurrentOnlineCode('__free__');
                      }}
                      style={{ color: '#096DD9' }}
                    >
                      &nbsp;
                      <AreaChartOutlined />
                    </a>
                    F:
                    {utils.formatNumber(monitorData?.totalFreeUserCount)} /
                    <a
                      key="online_chart_vip"
                      onClick={(e) => {
                        setFormOnlineVisible(true);
                        setCurrentGroup(undefined);
                        setCurrentOnlineCode('__vip__');
                      }}
                      style={{ color: '#096DD9' }}
                    >
                      &nbsp;
                      <AreaChartOutlined />
                    </a>
                    V:
                    {utils.formatNumber(monitorData?.totalVipUserCount)}]
                  </b>
                </Tag>
                服务器&nbsp;
                <Tag color="blue">
                  <b>
                    {/* {utils.formatNumber(totalValidServerCount)} /{' '}
                {utils.formatNumber(totalServerCount)} */}
                    {utils.formatNumber(monitorData?.totalValidServerCount)} /{' '}
                    {utils.formatNumber(monitorData?.totalServerCount)}
                  </b>
                </Tag>
              </span>

              <span>
                <Button
                  type="primary"
                  key="check"
                  // danger
                  onClick={() => {
                    setFormCheckVisible(true);
                  }}
                >
                  {/* <ArrowDownOutlined /> */}
                  下发检测
                </Button>
                &nbsp;
                <Button
                  // type="primary"
                  key="check_report"
                  onClick={() => {
                    setCurrentVer(undefined);
                    setFormCheckReportVisible(true);
                  }}
                >
                  检测结果
                </Button>
                &nbsp;
                <Button
                  key="check_task"
                  onClick={() => {
                    setFormCheckTaskVisible(true);
                  }}
                >
                  N
                </Button>
                &nbsp;
                <TableDropdown
                  key="actionServerMonitor"
                  // onSelect={(key) => {
                  //   // console.log(key);
                  //   switch(key){
                  //     case "export_ip":
                  //       setFormExportIpVisible(true);
                  //       break;
                  //   }
                  // }}
                  menus={[
                    {
                      key: 'filter_area_policy',
                      name: (
                        <span>
                          地区策略：
                          <Radio.Group defaultValue="a" buttonStyle="solid">
                            <Radio.Button
                              value="a"
                              onClick={() => {
                                handleFilterAreaPolicy(undefined);
                              }}
                            >
                              全部
                            </Radio.Button>
                            <Radio.Button
                              value="b"
                              onClick={() => {
                                handleFilterAreaPolicy(1);
                              }}
                            >
                              伊朗显示
                            </Radio.Button>
                            <Radio.Button
                              value="c"
                              onClick={() => {
                                handleFilterAreaPolicy(2);
                              }}
                            >
                              伊朗隐藏
                            </Radio.Button>
                          </Radio.Group>
                        </span>
                      ),
                    },
                    {
                      key: 'display_policy',
                      name: (
                        <span>
                          显示禁用：
                          <CheckableTag
                            key="disableGroup"
                            // style={{backgroundColor:"#1890FF"}}
                            checked={selectedTags.includes('group')}
                            onChange={(checked) =>
                              handleTagChange('group', checked)
                            }
                          >
                            <div
                              style={{
                                height: 30,
                                paddingTop: 5,
                                fontSize: 14,
                              }}
                            >
                              服务器分组
                            </div>
                          </CheckableTag>
                          <CheckableTag
                            key="disableServer"
                            // style={{backgroundColor:"#1890FF"}}
                            checked={selectedTags.includes('server')}
                            onChange={(checked) =>
                              handleTagChange('server', checked)
                            }
                          >
                            <div
                              style={{
                                height: 30,
                                paddingTop: 5,
                                fontSize: 14,
                              }}
                            >
                              服务器
                            </div>
                          </CheckableTag>
                        </span>
                      ),
                    },
                    {
                      key: 'export_ip',
                      name: (
                        <span>
                          　　操作：
                          <Button
                            key="btn_export_ip"
                            type="primary"
                            onClick={() => {
                              setFormExportIpVisible(true);
                            }}
                          >
                            导IP
                          </Button>
                        </span>
                      ),
                    },
                  ]}
                >
                  <Button>
                    <EllipsisOutlined />
                  </Button>
                </TableDropdown>
              </span>

              <span>
                <Countdown
                  title=""
                  key="cdRefresh"
                  value={countdownTicks}
                  format="s"
                  prefix=""
                  suffix="秒"
                  valueStyle={{
                    fontSize: 14,
                    color: 'gray',
                  }}
                  // style={{ visibility: countdownVisible }}
                  onFinish={reload}
                />
              </span>
              <span>
                <a
                  onClick={() => {
                    setDataLoading(true);
                    reload();
                  }}
                >
                  <ReloadOutlined />
                </a>
              </span>
              {/* <span>
      <Select
        defaultValue={60}
        style={{ width: 80 }}
        options={[
          {
            label: '禁止',
            value: 0,
          },
          // {
          //   label: '30秒',
          //   value: 30,
          // },
          {
            label: '60秒',
            value: 60,
          },
          {
            label: '120秒',
            value: 120,
          },
          {
            label: '300秒',
            value: 300,
          },
        ]}
        onChange={(val) => {
          if (val == 0) {
            setCountdownVisible('hidden');
            setCountdownTicks(-1);
          } else {
            if (countdownVisible == 'hidden') {
              setCountdownVisible('visible');
              setCountdownTicks(Date.now() + val * 1000);
              //actionRef.current?.reload();
            } else {
              setCustomCountdownTicks(val * 1000);
              setCountdownTicks(Date.now() + val * 1000);
              //actionRef.current?.reload();
            }
          }
        }}
      />
    </span> */}
            </Space>
          </Space>,
        ]}
        // toolbar={undefined}
        // toolbar={{
        //   menu: {
        //     type: 'tab',
        //     activeKey: productId,
        //     items: productMenuItems,
        //     onChange: (tabKey) => {
        //       setProductId(tabKey as string);
        //     },
        //   },
        // }}
        dataSource={monitorData?.data}
      />

      <VpnServerForm
        visible={formVisible}
        defaultGroupIds={undefined}
        // current={undefined}
        loadNodeId={current?.id}
        // onSubmit={handleFormSubmit}
        onSubmit={() =>{
          setCurrent(undefined);
          setFormVisible(false);
          // actionRef.current?.reload();
          reload();
        }}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <GrafanaForm
        visible={formGrafanaVisible}
        group={currentNodeGroup}
        server={currentNode}
        urlGrafana={currentUrlGrafana}
        groups={levelGroups}
        grafanaTitle={grafanaTitle}
        onCancel={() => {
          setFormGrafanaVisible(false);
          setCurrentNode(undefined);
          setCurrentNodeGroup(undefined);
          setCurrentUrlGrafana(undefined);
          setLevelGroups(undefined);
          setGrafanaTitle(undefined);
        }}
      />
      <CheckForm
        visible={formCheckVisible}
        groupIds={checkGroupIds}
        // groups={checkGroups}
        servers={checkServers}
        serverType={1}
        instIds={checkServerInstIds}
        onCancel={() => {
          setFormCheckVisible(false);
        }}
        onSubmit={checkFormSubmit}
      />
      <CheckReportForm
        visible={formCheckReportVisible}
        ver={currentVer}
        groupId={currentNodeGroup?.id}
        onCancel={() => {
          setFormCheckReportVisible(false);
          setCurrentNodeGroup(undefined);
          setCurrentVer(undefined);
        }}
        onCancelAndReload={() => {
          setFormCheckReportVisible(false);
          setCurrentNodeGroup(undefined);
          setCurrentVer(undefined);
        }}
      />
      <GroupForm
        visible={formGroupVisible}
        loadGroupId={undefined}
        current={currentGroup}
        parent={undefined}
        onSubmit={handleFormGroupSubmit}
        onCancel={() => {
          setCountdownTicks(Date.now() + 60 * 1000);
          setFormGroupVisible(false);
          setCurrentGroup(undefined);
        }}
      />
      <OnlineForm
        visible={formOnlineVisible}
        current={currentGroup}
        code={currentOnlineCode}
        productId={productId}
        onCancel={() => {
          setFormOnlineVisible(false);
          setCurrentGroup(undefined);
        }}
      />
      <VpnServerExportIpForm
        visible={formExportIpVisible}
        onCancel={() => {
          setFormExportIpVisible(false);
        }}
      />
      <ReportIpForm
        visible={formReportIpVisible}
        current={current}
        group={currentGroup}
        onCancel={() => {
          setFormReportIpVisible(false);
          setCurrentGroup(undefined);
          setCurrent(undefined);
        }}
      />
      
      <CheckTaskForm
        visible={formCheckTaskVisible}
        groupIds={checkGroupIds}
        // groups={checkGroups}
        servers={checkServers}
        instIds={checkServerInstIds}
        onCancel={() => {
          setFormCheckTaskVisible(false);
        }}
        onSubmit={() => {
          setFormCheckTaskVisible(false);
          setCheckGroupIds([]);
          setCheckServerInstIds([]);
          // setCheckGroups([]);
          setCheckServers([]);
        }}
      />
      
      {/* <ChangeIpForm
        visible={formChangeIpVisible}
        instIds={undefined}
        groupIds={undefined}
        serverIds={undefined}
        onCancel={() => {
          setFormChangeIpVisible(false);
        }}
        onSubmit={() => {
          setFormChangeIpVisible(false);
        }}
      /> */}
    </PageContainer>
  );
};

export default VpnGroupTreeList;
